<template>
  <view class="index">
    <u-navbar
      :background="navbar.background"
      :border-bottom="false"
      :custom-back="customBack"
      :title="userInfo.orgName"
      :title-color="navbar.color"
      back-icon-color="#fff"
      back-icon-name="scan"
      title-width="300"
    >
      <view slot="right">
        <u-icon
          :color="navbar.color"
          name="arrow-down"
          style="margin-right: 20rpx"
          @click="switchCompanies"
        ></u-icon>
      </view>
    </u-navbar>
    <view class="bg"></view>
    <view class="center">
      <u-swiper
        :list="appRotationImgList"
        border-radius="15"
        class="u-swiper"
        height="300"
        name="imgUrl"
      ></u-swiper>
      <view class="iconList">
        <u-grid :border="false" :col="5" class="lz-grid">
          <u-grid-item v-for="(item, index) in mygrids" :key="index" @click="navigetTo(item)">
            <u-badge
              v-if="computedMarker(item.name, 'show')"
              :count="computedMarker(item.name)"
              :offset="[20, 20]"
            ></u-badge>
            <view :class="item.code" :style="item.color" class="iconfont lz-grid-iconfont"></view>
            <view class="grid-text">{{ $t(item.name) }}</view>
          </u-grid-item>
          <u-grid-item @click="moreList">
            <view
              class="iconfont lz-grid-iconfont icon-xitong"
              style="background-color: #bdbdbd"
            ></view>
            <view class="grid-text">{{ $t('更多') }}</view>
          </u-grid-item>
        </u-grid>
      </view>

      <uni-list class="iconList" style="min-height: 500rpx">
        <view class="lz-section">
          <u-icon :size="40" color="#00aaff" custom-prefix="lizhao-icon" name="shenpi"></u-icon>
          <text class="lz-text">{{ $t('最近使用的申请单') }}</text>
        </view>
        <uni-list-item
          v-for="(item, index) in application_deal_data"
          :key="index"
          :title="item.title"
          clickable
          showArrow
        >
          <view slot="body" class="lz-list-body" @click="applicationDetails(item)">
            <view class="lz-list-title lz-ellipsis-1">{{ item.title }}</view>
            <view class="lz-list-item lz-ellipsis-1">{{ $t('申请人') }}：{{ item.userName }}</view>
            <view class="lz-list-item lz-ellipsis-1">{{ $t('日期') }}：{{ item.createDate }}</view>
            <view class="lz-list-item lz-ellipsis-1">
              {{ $t('状态') }}：
              <text class="status">{{ item.statusName }}</text>
            </view>
          </view>
        </uni-list-item>
        <u-empty
          v-if="application_deal_data.length === 0"
          :text="$t('暂无数据')"
          mode="list"
          style="padding: 20px 0"
        ></u-empty>
      </uni-list>
    </view>

    <u-picker
      v-model="picker.show"
      :default-selector="[0]"
      :range="picker.data"
      :title="$t('选择公司')"
      mode="selector"
      range-key="name"
      safe-area-inset-bottom
      @confirm="pickerConfirm"
    ></u-picker>
    <u-modal
      ref="uModal"
      v-model="modal.show"
      :title="$t('印章S号')"
      async-close
      show-cancel-button
      @confirm="modalConfirm"
    >
      <view class="slot-content">
        <u-form label-width="120rpx">
          <u-form-item :label="$t('印章S号')" style="padding: 20rpx 30rpx">
            <u-input v-model="modal.deviceid" />
          </u-form-item>
        </u-form>
      </view>
    </u-modal>
    <versionUpdate ref="versionUpdate"></versionUpdate>
    <u-no-network></u-no-network>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
import MescrollBodyDiy from '@/uni_modules/mescroll-uni/components/mescroll-diy/taobao/mescroll-body.vue'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
import { requestAndroidPermission } from '@/uni_modules/x-perm-apply-instr/js_sdk/index.js'

export default {
  mixins: [MescrollMixin],
  components: {
    MescrollBodyDiy
  },
  computed: {
    ...mapGetters(['userInfo', 'api']),
    computedMarker() {
      return (name, type) => {
        if (name === '审批处理' && this.Marker.obj.myPendingManagers) {
          if (type === 'show') {
            //当前是否显示
            return true
          } else {
            return this.Marker.obj.myPendingManagers
          }
        } else if (name === '授权处理' && this.Marker.obj.myPendingKeepers) {
          if (type === 'show') {
            //当前是否显示
            return true
          } else {
            return this.Marker.obj.myPendingKeepers
          }
        } else if (name === '审计处理' && this.Marker.obj.myPendingAuditors) {
          if (type === 'show') {
            //当前是否显示
            return true
          } else {
            return this.Marker.obj.myPendingAuditors
          }
        } else if (name === '我的申请' && this.Marker.obj.myPendingApplications) {
          if (type === 'show') {
            //当前是否显示
            return true
          } else {
            return this.Marker.obj.myPendingApplications
          }
        }
      }
    }
  },
  data() {
    return {
      //下拉配置
      downOption: {
        textInOffset: this.$t('继续下拉进入小程序'),
        textOutOffset: this.$t('释放可结束')
      },
      upOption: {
        use: false // 禁止上拉
      },
      navbar: {
        color: '#fff',
        background: {
          backgroundColor: '#0079FF'
        }
      },
      appRotationImgList: [], //轮播图
      mygrids: [],
      application_deal_data: [], //最近申请单
      Marker: {
        //角标
        obj: {}
      },
      picker: {
        //选择公司
        show: false,
        data: []
      },
      modal: {
        num: '',
        show: false,
        deviceid: ''
      },
      SystemInfoSync: {}
    }
  },
  onLoad() {
    //获取设备生物认证方式
    //#ifdef APP-PLUS
    plus.runtime.getProperty(plus.runtime.appid, (inf) => {
      this.SystemInfoSync = inf
      this.SystemInfoSync.runtimeVersion = plus.runtime.version
    })
    this.checkIsSupportSoterAuthentication()
    //检测更新
    checkUpdate()
    //#endif
  },
  onShow() {

    //aes密码解密
    this.getStoragePassword()
    //#ifdef MP-WEIXIN
    uni.closeBluetoothAdapter()
    //#endif
    //获取当前app版本
    // #ifdef APP-PLUS
    this.$nextTick(() => {
      this.$refs.versionUpdate.plusReady()
    })
    //#endif
  },
  methods: {
    ...mapActions(['set_userInfo', 'set_userToken', 'SET_SUPPORTMODE']),
    //关闭二楼
    goback() {
      setTimeout(() => {
        this.$refs.mescrollRef.closeErlou()
      }, 1500)
    },
    // 下拉刷新的回调
    downCallback() {
      this.mescroll.endErr()
    },
    //获取设备生物认证方式
    checkIsSupportSoterAuthentication() {
      uni.checkIsSupportSoterAuthentication({
        success: (res) => {
          this.SET_SUPPORTMODE(res.supportMode)
        },
        fail: (err) => {
          //console.log(err);
        }
      })
    },
    strategypassword_check(password) {
      this.$u
        .post(this.api.GLOBAL_auth_strategypassword_check, {
          password: password
        })
        .then((res) => {
          if (res.code === 510) {
            //密码不符合规则
            uni.reLaunch({
              url: '../template/setPassword/setPassword'
            })
          } else {
            //获取轮播图
            this.appRotationImg()
          }
        })
        .catch((err) => {
          //获取轮播图
          this.appRotationImg()
        })
    },
    //aes密码解密
    getStoragePassword() {
      uni.getStorage({
        key: 'user_password',
        success: (res) => {
          let password = this.$lizhao.AES.DecryptECB(res.data.password, 'password')
          //检测密码规则
          this.strategypassword_check(password)
        },
        fail:()=> {
          //获取轮播图
          this.appRotationImg()
        }
      })
    },
    moreList() {
      uni.switchTab({
        url: '/pages/tabBar/application'
      })
    },
    //弹出层确定
    modalConfirm() {
      this.$u
        .post(this.api.GLOBAL_device_signet_unlock, {
          signetId: this.modal.deviceid
        })
        .then((res) => {
          this.$refs.uModal.clearLoading()
          if (res.code === 200) {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        })
    },
    //确定切换
    pickerConfirm(e) {
      //console.log(e);
      let orgId = this.picker.data[e].id
      this.$u
        .post(this.api.GLOBAL_auth_user_changeOrg, {
          orgId: orgId
        })
        .then((res) => {
          if (res.code === 200) {
            //stroe存储登陆用户信息
            this.set_userInfo(res.data)
            //stroe存储登陆用户信息
            this.set_userToken(res.data.token)
            //更新当前页数据
            //轮播数据
            this.appRotationImg()
          }
        })
    },
    applicationDetails(item) {
      let data = {
        clickItem: item,
        option: {
          name: '我的申请'
        }
      }
      uni.navigateTo({
        url:
          '/pages/application/applicationDetails/applicationDetails?data=' +
          encodeURIComponent(JSON.stringify(data))
      })
    },
    //点击宫格
    navigetTo(item) {
      //兼容旧版本
      if (!item.appType) {
        this.appRouter(item)
        return
      }
      //新版
      if (item.appType === 'app') {
        if (item.name === '印章S号' || item.name === '手动解锁') {
          this.modal.show = true
          return
        }
        uni.navigateTo({ url: item.url + '?name=' + item.name })
      } else if (item.appType === 'h5') {
        uni.navigateTo({
          url: '/pages/h5/webview/webview',
          events: {
            confirm(data) {
              //console.log(data);
            }
          },
          success(res) {
            res.eventChannel.emit('pagePramas', item)
          }
        })
      } else if (item.appType === 'mp') {
        //console.log(item);
      }
    },
    appRouter(item) {
      if (item.name === '使用记录') {
        uni.navigateTo({ url: '/pages/application/useRecords/useRecords?name=' + item.name })
      } else if (item.name === '申请用章') {
        uni.navigateTo({
          url: '/pages/application/applicationSeal/applicationSeal?name=' + item.name
        })
      } else if (item.name === '我的印章') {
        uni.navigateTo({
          url: '/pages/application/sealManagement/sealManagement?name=' + item.name
        })
      } else if (item.name === '印章指纹') {
        uni.navigateTo({
          url: '/pages/application/sealManagement/sealManagement?name=' + item.name
        })
      } else if (item.name === '手动解锁' || item.name === '印章S号') {
        this.modal.show = true
      } else if (item.name === '高拍仪') {
        uni.navigateTo({ url: '/pages/OCR/deviceBind/deviceBind?name=' + item.name })
      } else if (item.name === '智能OCR') {
        uni.navigateTo({ url: '/pages/OCR/intelligenceOcr/intelligenceOcr?name=' + item.name })
      } else if (item.name === '盖章记录') {
        uni.navigateTo({
          url: '/pages/electronicSeal/electronUsageRecord/electronUsageRecord?name=' + item.name
        })
      } else if (item.name === '电子印章') {
        uni.navigateTo({
          url: '/pages/electronicSeal/electronicSealList/electronicSealList?name=' + item.name
        })
      } else if (item.name === '合同管理') {
        uni.navigateTo({
          url: '/pages/electronicSeal/contractManagement/contractManagement?name=' + item.name
        })
      } else if (item.name === '电子印签') {
        uni.navigateTo({ url: '/pages/electronicSeal/electronicSeal?name=' + item.name })
      } else {
        uni.navigateTo({
          url: '/pages/application/applicationList/applicationList?name=' + item.name
        })
      }
    },
    //扫码
    customBack() {
      // 允许从相机和相册扫码
			requestAndroidPermission(['android.permission.CAMERA','android.permission.READ_EXTERNAL_STORAGE'], {
			    title: '相机/相册读取权限申请说明',
			    content: '为了识别二维码信息及相册图片,我们需要申请您设备的相机和存储权限。'
			}).then(status => {
				if(status === 1){
					uni.scanCode({
						success: (res) => {
							//console.log('条码内容：' + res.result);
							//获取章的信息
							this.checkBindPermissions(res.result)
						}
					})
				}
			})
    },

    checkBindPermissions(url) {
      //console.log('url', url)
      //console.log('getQueryString url', this.$lizhao.url.getQueryString(url, 'sn'))
      let sn = this.$u.trim(this.$lizhao.url.getQueryString(url, 'sn'))
      this.$u
        .get(this.api.GLOBAL_signet_findBySn, {
          sn: sn
        })
        .then((res) => {
          if (res.code === 200) {
            //当前登录用户不是章的管章人和所在公司是属主，则提示
            if (
              res.data.status === 4 &&
              res.data.keeperId !== this.userInfo.userId &&
              res.data.ownerId !== this.userInfo.userId
            ) {
              uni.showToast({
                title: this.$t('印章已锁定，请联系设备管理员或公司属主'),
                icon: 'none'
              })
              return
            }
            if (res.data.orgId) {
              //已绑定并且有权限
              uni.navigateTo({
                url: './bluetooth?data=' + encodeURIComponent(url) + '&from=扫码'
              })
            } else {
              //未绑定
              uni.navigateTo({
                url:
                  './bluetooth?data=' + encodeURIComponent(url) + '&from=设置wifi&afterTo=绑定组织'
              })
            }
          }
        })
        .catch((err) => {
          //console.log(err);
        })
    },
    //切换公司
    switchCompanies() {
      this.$u
        .post(this.api.GLOBAL_auth_org_getOrgsByLogin, {})
        .then((res) => {
          if (res.code === 200 && res.data) {
            this.picker.data = res.data
            if (res.data.length > 0) {
              this.picker.show = true
            } else {
              uni.showToast({
                title: this.$t('只有一个集团'),
                icon: 'none'
              })
            }
          }
        })
        .catch((err) => {
          //console.log(err);
        })
    },
    //轮播数据
    appRotationImg() {
      this.$u.post(this.api.GLOBAL_auth_appRotationImg_getAll, {}).then((res) => {
        if (res.code === 200 && res.data) {
          this.appRotationImgList = res.data
        }
        //获取角标
        this.cornerMark()
        //获取所有图标
        this.getPhoneIcons()
        //获取最近使用申请单
        this.getNearestApplication()
      })
    },
    //获取所有图标
    getPhoneIcons() {
      this.$u.post(this.api.GLOBAL_user_getPhoneIcons, {}).then((res) => {
        if (res.code === 200) {
          //已选择的应用
          this.mygrids = res.data.MyCoin
        }
      })
    },
    //获取最近使用申请单
    getNearestApplication() {
      this.$u.post(this.api.GLOBAL_application_getNearestApplication, {}).then((res) => {
        if (res.code === 200 && res.data) {
          this.application_deal_data = res.data
        } else {
          this.application_deal_data = []
        }
      })
    },
    //获取角标
    cornerMark() {
      this.$u.post(this.api.GLOBAL_application_getDataByOwner, {}).then((res) => {
        if (res.code === 200) {
          this.Marker.obj = res.data
        }
      })
    }
  }
}
</script>

<style lang="scss">
.index {
  height: 100%;

  .status_bar {
    height: var(--status-bar-height);
    width: 100%;
  }

  .bg {
    height: 300rpx;
    width: 100%;
    background: linear-gradient(to bottom, #0079ff 20%, #00c6ff);
    border-radius: 0 0 30% 30%;
    position: absolute;
    top: 44px;
  }

  .center {
    overflow: hidden;
    padding: 0 30rpx 110rpx;
    background-color: #f0f0f0;

    .u-swiper {
      width: 100%;
      margin: 110rpx auto 0;
    }

    .iconList {
      width: 100%;
      background-color: #fff;
      margin: 20rpx 0;
      border-radius: 20rpx;
      overflow: hidden;
    }
  }
}
</style>
